import { HttpException, HttpStatus, Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from './jwt.service';
import { UserEntity } from '../Employee/User.entity';
import { UserService } from '../Employee/user.service';

interface LoginPayload {
  userName: string;
  userPassword: string;
}


@Injectable()
export class AuthService {

  constructor(private readonly userService: UserService,
              private readonly jwtService: JwtService,
  ) {
  }

  async createToken(user: UserEntity) {
    delete user.userPassword;
    return {
      user,
      expiresIn: user ? 1 : process.env.JWT_EXPIRATION_TIME || 3600,
      accessToken: user ? await this.jwtService.sign(user) : undefined,
    };
  }

  async validateUserByName(payload: any): Promise<any> {
    if (payload?.userName) {
      const user = await this.userService.findOneByName(
        payload.userName,
      );
      console.log('user', user);
      if (!user) {
        throw new UnauthorizedException('Incorrect username or password');
      }
      return user;
    }
    return undefined;
  }


  /**
   * 根据用户名和密码验证用户身份。
   *
   * @param payload - 包含用户名和密码的对象。
   * @returns 返回一个包含用户信息和token的对象，如果验证失败则抛出异常。
   */
  async validateUserByNameAndPassword(payload: LoginPayload): Promise<any> {
    // 检查用户名和密码是否为空
    if (!payload.userName || !payload.userPassword) {
      throw new HttpException('Username or password cannot be empty', HttpStatus.UNAUTHORIZED);
    }

    // 根据用户名和密码查找用户
    const user = await this.userService.findOneByNameAndPassword(payload);

    // 如果找到用户，生成并返回token
    if (user) {
      return this.createToken(user);
    }

  }


}
